var layer = null;
layui.use(['layer', 'form'], function(){
    layer = layui.layer;
});

var ImSocket = {
    socketUrl:"",
    websocket:"",
    timeout: 30000,//30s
    timeoutObj: null,
    callback:function(msg){
        console.log("接收到的推送数据：" + JSON.stringify(msg));
    },
    onOpen:function(event) {

    },
    init:function(cb){
        //一些对浏览器的兼容已经在插件里面完成
        var websocket = new ReconnectingWebSocket(this.socketUrl);
        this.websocket = websocket;
        if (cb) {
            this.callback = cb;
        }

        //连接发生错误的回调方法
        websocket.onerror = function () {
            $.message("Socket连接建立失败!");
            console.log("websocket.error");
        };

        //连接成功建立的回调方法
        websocket.onopen = function (event) {
            console.log("Socket连接建立成功!");
            ImSocket.onOpen(event);
            ImSocket.keepAlive();
            //websocket.send(JSON.stringify(param));
        };

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            if ("_h_k_" == event.data) {
                return;
            }
            //this.reset();
            var data = eval('(' + event.data + ')');
            if (data.category == "im_type") {
                im.getMessage(eval('(' + data.message + ')'));
                return;
            }
            ImSocket.callback(data);
        };

        //连接关闭的回调方法
        websocket.onclose = function () {
            websocket.close();
            console.log("websocket.onclose");
        };

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        /*window.onbeforeunload = function () {
            websocket.close();
        };*/
        return websocket;
    },
    sendMsg:function(msg) {
        if (!msg) {
            console.log("WebSocket message is blank, not send !!!");
            return;
        }
        try {
            this.websocket.send(msg);
        } catch (e) {
            console.log(e);
        }
    },
    keepAlive:function(){
        var websocket = this.websocket;
        if (this.timeoutObj) {
            window.clearInterval(this.timeoutObj);
        }
        this.timeoutObj = setInterval(function () {
            //console.log("keep alive...");
            websocket.send("_h_k_");
        }, this.timeout);
    }
};

var im = {
    layim: "",
    currentImWindow:{},
    config: function (options) {
        layui.use('layim', function (layim) {
            im.layim = layim;
            options.callback ? options.callback(layim) : "";
            layim.config({
                brief: false,
                title: '在线聊天',
                min: true,
                initSkin: '2.jpg',
                isAudio: false,
                isVideo: false,
                notice: false,
                isfriend: true,
                isgroup: true,
                copyright: true,
                init: {//获取主面板列表信息
                    url: ImRequestUrls.initUrl, //接口地址
                    type: 'get', //默认get，一般可不填
                    data: {} //额外参数
                },
                members: {//获取群员接口
                    url: '', //接口地址
                    type: 'get', //默认get，一般可不填
                    data: {} //额外参数
                },
                uploadImage: {//上传图片接口（返回的数据格式见下文），若不开启图片上传，剔除该项即可
                    url: ImRequestUrls.uploadFileUrl, //接口地址
                    type: 'post' //默认post
                },
                uploadFile: {//上传文件接口（返回的数据格式见下文），若不开启文件上传，剔除该项即可
                    url: ImRequestUrls.uploadFileUrl, //接口地址
                    type: 'post' //默认post
                },
                //msgbox: layui.cache.dir + 'css/modules/layim/html/msgbox.html', //消息盒子页面地址，若不开启，剔除该项即可
                find: ImRequestUrls.findUrl, //发现页面地址，若不开启，剔除该项即可
                chatLog: ImRequestUrls.chatLogUrl //聊天记录页面地址，若不开启，剔除该项即可
            });
        });
    },
    eventListener: function () {//事件监听
        var layim = this.layim;

        //ready事件
        layim.on('ready', function (options) {
            //console.log(JSON.stringify(options));
            /*var cache =  layui.layim.cache();
            console.log(cache);
            cache.local = {};
            var local = layui.data('layim')[cache.mine.id]; //获取当前用户本地数据
            delete cache;
            layui.data('layim', {
                key: cache.mine.id
                ,value: {}
            });*/
        });

        //监听在线状态切换
        layim.on('online', function (status) {
            $.ajaxRequest({
                type : 'post',
                url : ImRequestUrls.modifyOnlineStatusUrl,
                data:{state:status},
                success : function(data) {
                    if (!data.success) {
                        $.message(data.message);
                    }
                }
            });
        });

        //监听修改签名
        layim.on('sign', function (value) {
            $.ajaxRequest({
                type : 'post',
                url : ImRequestUrls.modifySign,
                data:{sign:value},
                success : function(data) {
                    if (!data.success) {
                        $.message(data.message);
                    }
                }
            });
        });

        //监听更换背景皮肤
        layim.on('setSkin', function (filename, src) {
            console.log(filename); //获得文件名，如：1.jpg
            //console.log(src); //获得背景路径，如：http://res.layui.com/layui/src/css/modules/layim/skin/1.jpg
        });

        //监听发送的消息
        layim.on('sendMessage', function (res) {
            var mine = res.mine; //包含我发送的消息及我的信息
            var to = res.to; //对方的信息
            var message = {
                username:mine.username,
                avatar:mine.avatar,
                id:mine.id,
                type: to.type,
                content:mine.content,
                mine:false,
                fromid:mine.id,
                friendId:to.id,
                userId:mine.id
            };

            $.ajaxRequest({
                type : 'post',
                url : ImRequestUrls.sendMessage,
                data:message,
                success : function(data) {
                    if (!data.success) {
                        $.message(data.message);
                    }
                }
            });
        });

        //监听聊天窗口的切换
        layim.on('chatChange', function(obj){
            im.currentImWindow = obj;
            //console.log(JSON.stringify(obj));
        });
    },
    getMessage: function (data) {//设置im推送过来的消息
        if (data.mine == "false") {
            data.mine = false;
        }
        this.layim.getMessage(data);
    },
    init: function () {
        this.config({
            callback:function(layim){
                im.eventListener();
            }
        });
    }
};